package com.etc.week4_day04_boot_ssm.controller;

import com.etc.week4_day04_boot_ssm.entity.Article;
import com.etc.week4_day04_boot_ssm.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Article控制器
 */
@RestController
public class ArticleController {

    @Autowired
    private ArticleService service;

    /**
     * rest风格演示： 查询操作 GetMapping
     *
     * @param id
     * @return
     */
    @GetMapping("article/{id}")
    public Article getById(@PathVariable("id") Long id) {
        Article article = service.selectById(id);
        return article;
    }

    /**
     * rest风格演示： 查询操作 GetMapping
     *
     * @param article
     * @param page
     * @param pagesize
     * @return
     */
    @GetMapping("article/{page}/{pagesize}")
    public List<Article> getByLike(Article article, @PathVariable(name = "page", required = false) int page, @PathVariable(name = "pagesize", required = false) int pagesize) {

        if (article == null) {
            article = new Article();
        } else {
            if (article.getTitle() != null) {
                article.setTitle("%" + article.getTitle() + "%");
            }
            // ... 省略其他属性
        }
        List<Article> articles = service.selectByLike(article, page, pagesize);
        return articles;
    }


    /**
     * rest风格演示： 增加操作 PostMapping
     *
     * @param article
     * @return
     */
    @PostMapping("article")
    public int add(@RequestBody() Article article) {

        //校验省略....
        int result = service.add(article);
        return result;
    }

    /**
     * rest风格演示： 修改操作 PutMapping
     *
     * @param article
     * @return
     */

    @PutMapping("article")
    public int update(@RequestBody() Article article) {

        //校验省略....
        int result = service.updateById(article);
        return result;
    }

    /**
     * rest风格演示： 删除 DeleteMapping
     *
     * @param id
     * @return
     */
    @DeleteMapping("article/{id}")
    public int deleteById(@PathVariable("id") Long id) {

        //校验省略....
        int result = service.deleteById(id);
        return result;
    }

}
